<?php

use think\Db;

/**
 * 小程序验证敏感字
 */
function checkText($content = '')
{
    $xcxConfig = db('xcx_config')->find(1);
    $APPID = $xcxConfig['appid']; // 替换为你的小程序 appid
    $AppSecret = $xcxConfig['secret']; // 替换为你的小程序 secret
    $token = $xcxConfig;
    if (empty($token) || empty($token['access_token']) || $token['exp_time'] < time()) {
        $access_token = getAccessToken();
        db('xcx_config')->where('id', 1)->update(['access_token' => $access_token, 'exp_time' => time() + 7000]);
        $token = db('xcx_config')->find(1);
    }

    $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $token['access_token'];
    $json_data = '{"content":"' . $content . '"}';

    $result = PublicCurl($url, true, 'post', $json_data);

    $result = json_decode($result, 1);

    if ($result['errcode'] == 87014) {
        return ['Code' => 0, 'msg' => '涉及敏感词'];
    } else {
        return ['Code' => 1, 'msg' => '文本正常'];
    }
}
/**
 * [PublicCurl 发送CURL请求]
 * @param string  $url    [请求地址]
 * @param boolean $https  [是否为https]
 * @param string  $method [请求方式 post|get]
 * @param string  $data   [请求数据json字符串]
 * @param array   $header [头信息中的参数]
 */
function PublicCurl($url = '', $https = true, $method = 'get', $data = null, $header = array())
{
    //1.初始化url
    $ch = curl_init($url);
    //2.设置相关的参数
    //字符串不直接输出,进行一个变量的存储
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //判断是否为https请求
    if ($https === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    //判断是否为post请求
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //判断是否为delete请求
    if ($method == 'delete') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //判断是否有http头参数
    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    //3.发送请求
    $str = curl_exec($ch);
    //4.关闭连接
    curl_close($ch);
    //返回请求到的结果
    return $str;
}
//获取access_token
function getAccessToken()
{

    $xcxConfig = db('xcx_config')->find(1);
    $appid = $xcxConfig['appid']; // 替换为你的小程序 appid
    $secret = $xcxConfig['secret']; // 替换为你的小程序 secret
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $res = curl_exec($curl);
    curl_close($curl);
    return json_decode($res)->access_token;
}
function get_city_name($id) {
    $name = Db::name('area')->where('id',$id)->value('name');
    return $name;
}